﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace RevCounterSerial
{
    public partial class Form1 : Form
    {
        private static SerialPort arduinoPort;

        public Form1()
        {
            InitializeComponent();

            // Set up the serial port for comms with the Arduino board
            arduinoPort = new SerialPort();
            arduinoPort.PortName = "COM3";
            arduinoPort.BaudRate = 9600;
            arduinoPort.Open();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Arduino needs DTR apparently
            arduinoPort.DtrEnable = true;

            // This is the flashing LEDs code from the first
            // Arduino sketch, but this time we're controlling
            // it from C# on the PC
            int delayTime = 100;  // delay 1/10 sec before each update
            int flashTime = 100;  // flash all the LEDs with 1/2 dec delay
            byte value = 0;          // this is the value written to the 595
            updateLEDs(0);
            for (byte i = 0; i < 8; i++)
            {
                value = (byte)(value | (1 << i));
                updateLEDs(value);
                Thread.Sleep(delayTime);
            }
            // Flash the LEDs to mimick full revs
            for (int j = 0; j < 4; j++)
            {
                updateLEDs(255);
                Thread.Sleep(flashTime);
                updateLEDs(0);
                Thread.Sleep(flashTime);
            }
        }

        private void updateLEDs(byte value)
        {
            // Send the byte value for the LEDs to the 
            // serial port attached to the Arduino
            arduinoPort.Write(new byte[] {value}, 0, 1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
